package org.ls.petclinic.web;

import cn.hutool.core.util.ObjectUtil;
import com.google.gson.Gson;
import org.ls.petclinic.dao.PetsDao;
import org.ls.petclinic.dao.TypeDao;
import org.ls.petclinic.dao.VisitsDao;
import org.ls.petclinic.dao.impl.PetsDaoImpl;
import org.ls.petclinic.dao.impl.TypeDaoImpl;
import org.ls.petclinic.dao.impl.VisitsDaoImpl;
import org.ls.petclinic.pojo.Pets;
import org.ls.petclinic.pojo.Type;
import org.ls.petclinic.pojo.Visits;
import org.ls.petclinic.pojo.vo.VisitsVo;
import org.ls.petclinic.untils.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 浪矢先生
 * @description
 * @create 2022-12-05 22:03
 */
@WebServlet(urlPatterns = "/getVisit")
public class GetVisits extends BaseServlet {
    private VisitsDao visitsDao = new VisitsDaoImpl();
    private PetsDao petsDao=new PetsDaoImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Gson gson = new Gson();
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        String petId = req.getParameter("petId");
        List<VisitsVo> result=new ArrayList<>();
        if (!ObjectUtil.isNull(petId)){
            long l = Long.parseLong(petId);
            List<Visits> byPetId = visitsDao.getByPetId(l);
            for (Visits visits : byPetId) {
                VisitsVo visitsVo = new VisitsVo();
                visitsVo.setId(visits.getId());
                visitsVo.setVisitDate(visits.getVisitDate());
                visitsVo.setDescription(visits.getDescription());
                result.add(visitsVo);
            }
        }else {
            List<Visits> all = visitsDao.all();
            for (Visits visits : all) {
               Pets pet =  petsDao.getById(visits.getPetId());
                VisitsVo visitsVo = new VisitsVo();
                visitsVo.setPet(pet);
                visitsVo.setVisitDate(visits.getVisitDate());
                visitsVo.setDescription(visits.getDescription());
                visitsVo.setId(visits.getId());
                result.add(visitsVo);
            }
        }
        JdbcUtils.commitAndClose();
        resp.getWriter().write(String.valueOf(gson.toJson(result)));
    }
}
